package nl.liacs.mms.dn.server;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.liacs.mms.dn.entities.DigitalNote;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

@SuppressWarnings("serial")
public class DigitalNotesUploadServlet extends HttpServlet {

	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	private DigitalNotesService notesService = new DigitalNotesService();

	/**
	 * returns the url which is used for the post request
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String url = blobstoreService.createUploadUrl("/upload");
		res.setContentType("text/plain");
		res.getWriter().write(url);
	}

	/**
	 * this function stores the digital note
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

		// get digital note object from request
		DigitalNote dn = notesService.RequestToDigitalNote(req);

		// generate blob object and key for image
		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);

		// add image if uploaded
		if (blobs.get("image") != null) {
			BlobKey blobKey = blobs.get("image").get(0);
			if (blobKey == null) {
				res.sendRedirect("/error");
			}

			// save blob key in digital note object
			dn.setImageKey(blobKey);
		}

		// save digital note in datastore
		notesService.saveDigitalNote(dn);

		// set status created if successful
		res.setStatus(201);
		res.getWriter().write("success");
	}

}
